using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;

namespace ERP_SaaS_WinForm.采购管理
{
    /// <summary>
    /// 质检人员选择弹窗
    /// </summary>
    public partial class InspectorSelectionForm : Form
    {
        /// <summary>
        /// 选中的质检人员信息
        /// </summary>
        public InspectorInfo SelectedInspector { get; private set; }
        
        /// <summary>
        /// 是否确认选择
        /// </summary>
        public bool IsConfirmed { get; private set; }

        public InspectorSelectionForm()
        {
            InitializeComponent();
            this.Load += InspectorSelectionForm_Load;
        }

        private async void InspectorSelectionForm_Load(object sender, EventArgs e)
        {
            try
            {
                await LoadInspectors();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载质检人员数据失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 加载质检人员数据
        /// </summary>
        private async Task LoadInspectors()
        {
            try
            {
                string apiUrl = "http://localhost:5117/api/Supplier/GetUserInfo";
                
                using (HttpClient client = new HttpClient())
                {
                    var response = await client.GetAsync(apiUrl);
                    response.EnsureSuccessStatusCode();
                    string jsonResponse = await response.Content.ReadAsStringAsync();
                    
                    var apiResponse = JsonConvert.DeserializeObject<UserApiResponse>(jsonResponse);
                    
                    if (apiResponse.code == 200 && apiResponse.data != null && apiResponse.data.Count > 0)
                    {
                        // 清空现有数据
                        dgvInspectors.Rows.Clear();
                        
                        // 添加用户数据（质检人员）
                        foreach (var user in apiResponse.data)
                        {
                            int rowIndex = dgvInspectors.Rows.Add();
                            dgvInspectors.Rows[rowIndex].Cells["colInspectorId"].Value = user.userId;
                            dgvInspectors.Rows[rowIndex].Cells["colInspectorName"].Value = user.userName;
                            dgvInspectors.Rows[rowIndex].Cells["colInspectorCode"].Value = user.userCode ?? user.userId.ToString();
                            dgvInspectors.Rows[rowIndex].Cells["colDepartmentName"].Value = user.departmentName ?? "未指定部门";
                            dgvInspectors.Rows[rowIndex].Cells["colPhone"].Value = user.phone ?? "";
                            
                            // 转换为InspectorInfo对象保存
                            var inspector = new InspectorInfo
                            {
                                InspectorId = user.userId,
                                InspectorName = user.userName,
                                InspectorCode = user.userCode ?? user.userId.ToString(),
                                DepartmentName = user.departmentName ?? "未指定部门",
                                Phone = user.phone ?? ""
                            };
                            dgvInspectors.Rows[rowIndex].Tag = inspector;
                        }
                    }
                    else
                    {
                        // 如果API没有数据，添加一些测试数据
                        AddTestData();
                    }
                }
            }
            catch (Exception ex)
            {
                // API调用失败时，添加测试数据
                Console.WriteLine($"API调用失败，使用测试数据：{ex.Message}");
                AddTestData();
            }
        }

        /// <summary>
        /// 添加测试数据
        /// </summary>
        private void AddTestData()
        {
            var testInspectors = new List<InspectorInfo>
            {
                new InspectorInfo { InspectorId = 1, InspectorName = "张三", InspectorCode = "QC001", DepartmentName = "质检部", Phone = "13800138001" },
                new InspectorInfo { InspectorId = 2, InspectorName = "李四", InspectorCode = "QC002", DepartmentName = "质检部", Phone = "13800138002" },
                new InspectorInfo { InspectorId = 3, InspectorName = "王五", InspectorCode = "QC003", DepartmentName = "品控部", Phone = "13800138003" },
                new InspectorInfo { InspectorId = 4, InspectorName = "赵六", InspectorCode = "QC004", DepartmentName = "质检部", Phone = "13800138004" },
                new InspectorInfo { InspectorId = 5, InspectorName = "孙七", InspectorCode = "QC005", DepartmentName = "品控部", Phone = "13800138005" }
            };

            dgvInspectors.Rows.Clear();
            foreach (var inspector in testInspectors)
            {
                int rowIndex = dgvInspectors.Rows.Add();
                dgvInspectors.Rows[rowIndex].Cells["colInspectorId"].Value = inspector.InspectorId;
                dgvInspectors.Rows[rowIndex].Cells["colInspectorName"].Value = inspector.InspectorName;
                dgvInspectors.Rows[rowIndex].Cells["colInspectorCode"].Value = inspector.InspectorCode;
                dgvInspectors.Rows[rowIndex].Cells["colDepartmentName"].Value = inspector.DepartmentName;
                dgvInspectors.Rows[rowIndex].Cells["colPhone"].Value = inspector.Phone;
                dgvInspectors.Rows[rowIndex].Tag = inspector;
            }
        }

        /// <summary>
        /// 确认选择按钮点击事件
        /// </summary>
        private void btnConfirm_Click(object sender, EventArgs e)
        {
            if (dgvInspectors.SelectedRows.Count > 0)
            {
                var selectedRow = dgvInspectors.SelectedRows[0];
                SelectedInspector = selectedRow.Tag as InspectorInfo;
                IsConfirmed = true;
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            else
            {
                MessageBox.Show("请选择一个质检人员！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        /// <summary>
        /// 取消按钮点击事件
        /// </summary>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            IsConfirmed = false;
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        /// <summary>
        /// 搜索按钮点击事件
        /// </summary>
        private void btnSearch_Click(object sender, EventArgs e)
        {
            string searchText = txtSearch.Text.Trim();
            if (string.IsNullOrEmpty(searchText))
            {
                // 如果搜索框为空，重新加载所有数据
                LoadInspectors();
                return;
            }

            // 过滤显示的数据
            foreach (DataGridViewRow row in dgvInspectors.Rows)
            {
                if (row.IsNewRow) continue;
                
                bool isMatch = false;
                string inspectorName = row.Cells["colInspectorName"].Value?.ToString() ?? "";
                string inspectorCode = row.Cells["colInspectorCode"].Value?.ToString() ?? "";
                string departmentName = row.Cells["colDepartmentName"].Value?.ToString() ?? "";
                
                if (inspectorName.Contains(searchText) || 
                    inspectorCode.Contains(searchText) || 
                    departmentName.Contains(searchText))
                {
                    isMatch = true;
                }
                
                row.Visible = isMatch;
            }
        }

        /// <summary>
        /// 双击行选择
        /// </summary>
        private void dgvInspectors_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                btnConfirm_Click(sender, e);
            }
        }
    }

    /// <summary>
    /// 质检人员信息模型
    /// </summary>
    public class InspectorInfo
    {
        public int InspectorId { get; set; }
        public string InspectorName { get; set; }
        public string InspectorCode { get; set; }
        public string DepartmentName { get; set; }
        public string Phone { get; set; }
    }

    /// <summary>
    /// 用户信息API响应结果
    /// </summary>
    public class UserApiResponse
    {
        public string msg { get; set; }
        public int code { get; set; }
        public List<UserInfo> data { get; set; }
    }

    /// <summary>
    /// 用户信息模型（来自API）
    /// </summary>
    public class UserInfo
    {
        public int userId { get; set; }
        public string userName { get; set; }
        public string userCode { get; set; }
        public string departmentName { get; set; }
        public string phone { get; set; }
        public string email { get; set; }
        public string position { get; set; }
    }
}
